package com.polimi.meteocal.security;

import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.enterprise.context.SessionScoped;
import javax.faces.bean.ManagedBean;
import javax.faces.event.ActionEvent;

import com.polimi.meteocal.business.control.InviteManager;
import com.polimi.meteocal.business.control.PartecipationManager;
import com.polimi.meteocal.business.control.UserManager;
import com.polimi.meteocal.business.entity.Ack;
import com.polimi.meteocal.business.entity.Invite;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@ManagedBean
@SessionScoped
public class PendantInvitesBean implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	@EJB
	InviteManager im;
	@EJB
	UserManager um;
	@EJB
	PartecipationManager pm;
	
	private List<Invite> pendantInvites;
	private boolean decision;
	
	@PostConstruct
	public void init(){
		System.out.println("INIT PendantInvitesBean");
		
		//Get invitesReceived
		List<Invite> invitesReceived= im.getUserInviteList();
		
		
		//Get acks
		Ack aFi= new Ack();
		List<Ack> acksForUser= new ArrayList<Ack>();
		
		for(Invite i: invitesReceived){
			
				if(pm.getPartecipation(i.getEvent().getId(), i.getUser1(), i.getUser2())!=null){
					
					aFi=pm.getPartecipation(i.getEvent().getId(), i.getUser1(), i.getUser2());
					acksForUser.add(aFi);
				}
			
		}
		
		
		
		
		
		//Set pendantInvites
		List<Invite> pInv= new ArrayList<Invite>();
		
		boolean contains= false;
		
		for(Invite i: invitesReceived){
			for(Ack a: acksForUser){
				if(a.getInvite().getEvent().getId()==i.getEvent().getId()){
					contains=true;
				}
			}
			
			if(!contains){
				
				pInv.add(i);
			}
			contains=false;
		}
			
		
		this.pendantInvites= pInv;
		
		
	}
	
	public void setPartecipation(ActionEvent event){
		System.out.println("SET PARTECIPATION");
		System.out.println("Decision: "+this.decision);
		
		Invite inv= (Invite) event.getComponent().getAttributes().get("invite");
		System.out.println("About invite: "+inv.getEvent().getName());
		String response;
		
		if(this.decision){
			response= "ACCEPT";
		}
		else{
			response= "REFUSE";
		}
		
		Ack ack= new Ack();
		ack.setInvite(inv);
		ack.setResponse(response);
		
		System.out.println("Resume: "+ack.getInvite().getEvent().getName()+"-->"+ack.getResponse());
		
		pm.setPartecipation(ack);
		
		
	}
	
	
	public String reloadPage(){
		return "calendarPage";
	}
	
	public List<Invite> getPendantInvites() {
		return pendantInvites;
	}

	public void setPendantInvites(List<Invite> pendantInvites) {
		this.pendantInvites = pendantInvites;
	}


	public boolean isDecision() {
		return decision;
	}


	public void setDecision(boolean decision) {
		this.decision = decision;
	}

}
